<?php

// +----------------------------------------------------------------------

// | Description: 客保部---员工评分和店面评分导出的页面逻辑

// +----------------------------------------------------------------------

// | Author: zl

// +----------------------------------------------------------------------



namespace app\crm\controller;



use app\admin\controller\ApiCommon;

use app\crm\model\BalanceLog;

use app\crm\model\CustomerAnalyseModel;
use app\crm\model\Setting;

use app\crm\model\SettingCategory;

use app\crm\model\Service;

use app\crm\model\ReturnVist;

use app\crm\model\ReturnVistT;

use app\crm\model\Customer as CustomerModel;

use app\crm\model\TransferShop;

use app\crm\model\CustomerConfig as CustomerConfigModel;

use app\crm\model\CustomerGrade as CustomerGradeModel;

use think\response\Json;

use think\facade\Db;

use app\admin\model\Coupon as CouponModel;

use app\common\traits\ActionRecordTrait;

use app\crm\model\CustomerInfoAPI as CustomerInfoAPIModel;//引用EC接口文档

use app\crm\model\ReserveandLost;

use app\crm\model\SendMsgModel;


class CustomerYucun extends ApiCommon

{
    protected $customerModel;

    protected $customerConfigModel;

    /**

     * 用于判断权限

     * @permission 无限制

     * @allow 登录用户可访问

     * @other 其他根据系统设置

     **/

    public function initialize()

    {

        $action = [

            'permission' => ['setCustomerZTYuCun','setCustomerKXYuCun','setCustomerDJYuCun','setjsmaktingyc','setzxunmaktingyc','setjmbjmaktingyc','setCustomerCYYuCun','setzgtmaktingyc','setcdcqmaktingyc','setCustomerJSYuCun','setCustomerZCYYuCun','setCustomerBJYYuCun','setCustomerZHUXUNYuCun','setcustomeryucunkunming','setztmaktingyc','setkmxianmaktingyc','setdjmaktingyc','setcustomerdongbei','customer_tj','set_ceshi','execute'],

            'allow' => ['users', 'info']

        ];

        event('CheckAuth',$action);

        $request = $this->request;

        $a = strtolower($request->action());



        $this->customerModel = new CustomerModel();

        $this->customerConfigModel = new CustomerConfigModel();

        if (!in_array($a, $action['permission'])) {

            parent::initialize();

        }

    }


	//郑太市场预存 -- 郑州直管3 + 郑州直营(含中医院)3+太原3   郑州万达+正弘店+金水总院+公园茂店+航海路+ 云路街+体育路+平阳路 +中医院
   public function setCustomerZTYuCun(){

	    //echo '客户预存信息页面';echo '<br/>';
	    $time = date('Ymd');

	    $zyShopIds = [73782774859952,76520948050011,78870916600002,78852178480703,73782774813542,73782774707242,73782774791259,73782774742277,73782774881835];
	    //查询有预存的客户
		$zyB = Db::name('customer_balance')->where('shop_id','in',$zyShopIds)->distinct('customer_id')->column('customer_id');
		//查询当天时间这些门店 是否已经有客户新增成功
		$zyYC = Db::name('customer_balance_tj')->where('time','=',$time)->where('shop_id','in',$zyShopIds)->distinct('customer_id')->column('customer_id');

		//客户ID进行去重
		$customerIds = array_diff($zyB, $zyYC);
		
		$zyByc = Db::name('customer_balance')->where('customer_id','in',$customerIds)->column('customer_id,balance_category_id,money,complimentary_money,shop_transfer_money,shop_id');
		
	    $b = ['time'=>$time];
	    array_walk($zyByc, function(&$val, $key) use ($b) {
	       $val = array_merge($val, $b);
	    });

	   $res = Db::name('customer_balance_tj')->insertAll($zyByc);

	   return resultArray(['data'=>[],'error'=>'处理成功']);



   }
   	//昆西市场预存  昆明南宁 6 + 西安 4
	public function setCustomerKXYuCun(){
		$time = date('Ymd');

		$zyShopIds = [73782775132896,73782775140871,73782775247649,73782775295382,73782775222970,73782775241316,73782775206631,73782775392774,73782775131388];
		//查询有预存的客户
		$zyB = Db::name('customer_balance')->where('shop_id','in',$zyShopIds)->distinct('customer_id')->column('customer_id');
		//查询当天时间这些门店 是否已经有客户新增成功
		$zyYC = Db::name('customer_balance_tj')->where('time','=',$time)->where('shop_id','in',$zyShopIds)->distinct('customer_id')->column('customer_id');

		//客户ID进行去重
		$customerIds = array_diff($zyB, $zyYC);
		
		$zyByc = Db::name('customer_balance')->where('customer_id','in',$customerIds)->column('customer_id,balance_category_id,money,complimentary_money,shop_transfer_money,shop_id');
		
	    $b = ['time'=>$time];
	    array_walk($zyByc, function(&$val, $key) use ($b) {
	       $val = array_merge($val, $b);
	    });


		$res = Db::name('customer_balance_tj')->insertAll($zyByc);

		return resultArray(['data'=>[],'error'=>'处理成功']);
	}
	//东北 6 + 京津 3  + 成都门诊1
	public function setCustomerDJYuCun(){
		$time = date('Ymd');

		$zyShopIds = [73782775074894,73782775019638,73782775492343,73782775012531,73782775013838,73782775096910,73782775102252,73782775155221,73782775133028,73782775085647];
		//查询有预存的客户
		$zyB = Db::name('customer_balance')->where('shop_id','in',$zyShopIds)->distinct('customer_id')->column('customer_id');
		//查询当天时间这些门店 是否已经有客户新增成功
		$zyYC = Db::name('customer_balance_tj')->where('time','=',$time)->where('shop_id','in',$zyShopIds)->distinct('customer_id')->column('customer_id');

		//客户ID进行去重
		$customerIds = array_diff($zyB, $zyYC);
		
		$zyByc = Db::name('customer_balance')->where('customer_id','in',$customerIds)->column('customer_id,balance_category_id,money,complimentary_money,shop_transfer_money,shop_id');
		
	    $b = ['time'=>$time];
	    array_walk($zyByc, function(&$val, $key) use ($b) {
	       $val = array_merge($val, $b);
	    });

		$res = Db::name('customer_balance_tj')->insertAll($zyByc);

		return resultArray(['data'=>[],'error'=>'处理成功']);
	}
	//成都 4 +重庆 5  直营门店    江北店+沙坪坝+南坪店+大坪店+杨家坪 ++ 总府店+龙湖店+文殊店+菊乐店+环球店
	public function setCustomerCYYuCun(){
		$time = date('Ymd');

		$zyShopIds = [73782774937394,73782774939196,73782774982253,73782774973465,73782774988622,73782774957269,73782775030746,73782775078712,73782775070582];
		//查询有预存的客户
		$zyB = Db::name('customer_balance')->where('shop_id','in',$zyShopIds)->distinct('customer_id')->column('customer_id');
		//查询当天时间这些门店 是否已经有客户新增成功
		$zyYC = Db::name('customer_balance_tj')->where('time','=',$time)->where('shop_id','in',$zyShopIds)->distinct('customer_id')->column('customer_id');

		//客户ID进行去重
		$customerIds = array_diff($zyB, $zyYC);
		
		$zyByc = Db::name('customer_balance')->where('customer_id','in',$customerIds)->column('customer_id,balance_category_id,money,complimentary_money,shop_transfer_money,shop_id');
		
	    $b = ['time'=>$time];
	    array_walk($zyByc, function(&$val, $key) use ($b) {
	       $val = array_merge($val, $b);
	    });

		$res = Db::name('customer_balance_tj')->insertAll($zyByc);

		return resultArray(['data'=>[],'error'=>'处理成功']);
	}

	//济南5 +石家庄 5 
	public function setCustomerJSYuCun(){
		$time = date('Ymd');

		$zyShopIds = [73782775249465,73782775342427,73782776799504,73782775382480,73782775368291,73782775339453,73782775382138,73782775394959];
		//查询有预存的客户
		$zyB = Db::name('customer_balance')->where('shop_id','in',$zyShopIds)->distinct('customer_id')->column('customer_id');
		//查询当天时间这些门店 是否已经有客户新增成功
		$zyYC = Db::name('customer_balance_tj')->where('time','=',$time)->where('shop_id','in',$zyShopIds)->distinct('customer_id')->column('customer_id');

		//客户ID进行去重
		$customerIds = array_diff($zyB, $zyYC);
		
		$zyByc = Db::name('customer_balance')->where('customer_id','in',$customerIds)->column('customer_id,balance_category_id,money,complimentary_money,shop_transfer_money,shop_id');
		
	    $b = ['time'=>$time];
	    array_walk($zyByc, function(&$val, $key) use ($b) {
	       $val = array_merge($val, $b);
	    });

		$res = Db::name('customer_balance_tj')->insertAll($zyByc);

		return resultArray(['data'=>[],'error'=>'处理成功']);
	}
	
	//郑州直营4 +郑州直管 3+ 成都2（攀成钢+光环）+烟台莱山1    玉凤路+文化路+天明路+建设西路+三全路店+商业中心店+升龙城店
	public function setCustomerZCYYuCun(){
		$time = date('Ymd');
		
		$zyShopIds = [73782774822370,73782774813357,73782774896742,73782774880422,78872028809917,79085556716103,78808830816801,79958737536305,73782776396518,79234669613042];
		//查询有预存的客户
		$zyB = Db::name('customer_balance')->where('shop_id','in',$zyShopIds)->distinct('customer_id')->column('customer_id');
		//查询当天时间这些门店 是否已经有客户新增成功
		$zyYC = Db::name('customer_balance_tj')->where('time','=',$time)->where('shop_id','in',$zyShopIds)->distinct('customer_id')->column('customer_id');
	
		//客户ID进行去重
		$customerIds = array_diff($zyB, $zyYC);
		
		$zyByc = Db::name('customer_balance')->where('customer_id','in',$customerIds)->column('customer_id,balance_category_id,money,complimentary_money,shop_transfer_money,shop_id');
		
	    $b = ['time'=>$time];
	    array_walk($zyByc, function(&$val, $key) use ($b) {
	       $val = array_merge($val, $b);
	    });
	
		$res = Db::name('customer_balance_tj')->insertAll($zyByc);
	
		return resultArray(['data'=>[],'error'=>'处理成功']);
	}
	
	//加盟门店 8家（烟青潍坊8家）
	public function setCustomerBJYYuCun(){
		$time = date('Ymd');
	
		$zyShopIds = [73782776714906,73782776780645,73782776735183,73782776723608,73782776866322,78144422942919,78153925370743,73782775923594,73782775246614,73782775223895];
		//查询有预存的客户
		$zyB = Db::name('customer_balance')->where('shop_id','in',$zyShopIds)->distinct('customer_id')->column('customer_id');
		//查询当天时间这些门店 是否已经有客户新增成功
		$zyYC = Db::name('customer_balance_tj')->where('time','=',$time)->where('shop_id','in',$zyShopIds)->distinct('customer_id')->column('customer_id');
	
		//客户ID进行去重
		$customerIds = array_diff($zyB, $zyYC);
		
		$zyByc = Db::name('customer_balance')->where('customer_id','in',$customerIds)->column('customer_id,balance_category_id,money,complimentary_money,shop_transfer_money,shop_id');
		
	    $b = ['time'=>$time];
	    array_walk($zyByc, function(&$val, $key) use ($b) {
	       $val = array_merge($val, $b);
	    });
	
		$res = Db::name('customer_balance_tj')->insertAll($zyByc);
	
		return resultArray(['data'=>[],'error'=>'处理成功']);
	}
	
	//处理预存    
	/* 
	 @*  百花店+巩义店+石家庄门诊+济南门诊+重庆门诊+大学路+江北店
	 @*  十里铺已经闭店-2024-6月；新疆万达店 不在续费 关闭；光华店 闭店
	*/
	public function setCustomerZHUXUNYuCun(){  //
		$time = date('Ymd');
	
		$zyShopIds = [73782777060245,73782776104831,73782775377728,73782775392774,73782774991693,73782774834649,73782774982464,82102481001860,73782775159891];
		//查询有预存的客户
		$zyB = Db::name('customer_balance')->where('shop_id','in',$zyShopIds)->distinct('customer_id')->column('customer_id');
		//查询当天时间这些门店 是否已经有客户新增成功
		$zyYC = Db::name('customer_balance_tj')->where('time','=',$time)->where('shop_id','in',$zyShopIds)->distinct('customer_id')->column('customer_id');
	
		//客户ID进行去重
		$customerIds = array_diff($zyB, $zyYC);
		
		$zyByc = Db::name('customer_balance')->where('customer_id','in',$customerIds)->column('customer_id,balance_category_id,money,complimentary_money,shop_transfer_money,shop_id');
		
	    $b = ['time'=>$time];
	    array_walk($zyByc, function(&$val, $key) use ($b) {
	       $val = array_merge($val, $b);
	    });
	
		$res = Db::name('customer_balance_tj')->insertAll($zyByc);
	
		return resultArray(['data'=>[],'error'=>'处理成功']);
	}

	public function customer_tj()
	{
		$model = new ReserveandLost();

		$today = date('Y-m-d',time());

		$nowDate = date("Ymd",time());

		// 获取门店shop_ids
		$shop_ids = Db::name('shop')->where([['type','=',1],['status','=',1],['shop_type','=',2],['shop_id','<>','74076159037951']])->column('shop_id');

		$list = [];

		foreach ($shop_ids as $key => $value) {

			$where = [];

			array_push($where,['shop_id','=',$value]);

			array_push($where,['date','=',$nowDate]);

			$data = Db::name('customer_tj')->where($where)->select()->toArray();

			if($data){

			}else{

				$one = [];

				$shopIds = [];

				array_push($shopIds,$value);

				// 总成交顾客数
				$cj_customer = $model->cj_customer($shopIds,[]);

				// 保有顾客数
				$baoyou_customer = $model->baoyou_customer($cj_customer,$today);

				// 流失顾客数
				$lost_customer = $model->lost_customer($cj_customer,$today);

				// 流失预警顾客
				$warning_customer = $model->warning_customer($cj_customer,$today,'','','');


				$one['shop_id'] = $value;

				$one['date'] = $nowDate;

				$one['cj_customer_ids'] = implode(',',$cj_customer) ?? '';

				$one['baoyou_customer_ids'] = implode(',',$baoyou_customer) ?? '';

				$one['lost_customer_ids'] = implode(',',$lost_customer) ?? '';

				$one['warn_customer_ids'] = implode(',',$warning_customer) ?? '';

				$one['create_time'] = time();

				array_push($list,$one);

			}



		}

		// echo "<pre>";
		// print_r($list);
		// echo "</pre>";

		if($list){

			$res = Db::name('customer_tj')->insertAll($list);

		}

		return resultArray(['data'=>[],'error'=>'处理成功']);
		// var_dump($res);
	}

	public function set_ceshi()
	{
		$addDate = [
			'tag_name' => date("Y-m-d H:i:s",time()),
			'customer_id' => '141222',
			'staff_name' => 'zhangsan',
			'create_time' => date("Y-m=d H:i:s",time()),
			'type' => '0',
		];

		$res = Db::name('customer_tag')->insert($addDate);

		return resultArray(['data'=>[],'error'=>'处理成功']);
	}

	//处理品相信息
	public function setOrderGoodsAnalyse()
	{
		$extra = [170];

		$start_time = strtotime(date('Y-m-d',strtotime('-1 day')));
		$end_time = $start_time+24*60*60-1;

		Db::startTrans();
		try{
			$where = [];
			array_push($where,['b.status','=',2]);
			array_push($where,['a.goods_id','not in',$extra]);
			array_push($where,['b.deal_time','>=',$start_time]);
			array_push($where,['b.deal_time','<=',$end_time]);

			$res = Db::name('shop_order_goods')
				->field('b.shop_id,b.uid,a.goods_id,a.number,a.pay_price')
				->alias('a')
				->join('shop_order b','a.order_id = b.id','LEFT')
				// ->join('shop_goods c','a.goods_id = c.id')
				// ->join('shop d','a.shop_id = d.shop_id')
				->where($where)
				// ->group('b.shop_id,a.goods_id')
				->select()->toArray();
			$firstData = [];
			foreach($res as $value)
			{
				$arr = [];
				if(empty($firstData[$value['shop_id']][$value['goods_id']]))
				{
					$firstData[$value['shop_id']][$value['goods_id']]['number'] = 1;
					$firstData[$value['shop_id']][$value['goods_id']]['uid'] = [];
					array_push($firstData[$value['shop_id']][$value['goods_id']]['uid'],$value['uid']);
					$firstData[$value['shop_id']][$value['goods_id']]['repurchase_num'] = 1;
					$firstData[$value['shop_id']][$value['goods_id']]['total_amount'] = $value['number']*$value['pay_price'];
				}else{
					$firstData[$value['shop_id']][$value['goods_id']]['number'] += 1;
					$firstData[$value['shop_id']][$value['goods_id']]['repurchase_num'] += 1;
					if(!in_array($value['uid'],$firstData[$value['shop_id']][$value['goods_id']]['uid']))
					{
						array_push($firstData[$value['shop_id']][$value['goods_id']]['uid'],$value['uid']);
					}
					$firstData[$value['shop_id']][$value['goods_id']]['total_amount'] += $value['number']*$value['pay_price'];
				}
			}
			$insertData = [];
			foreach($firstData as $key => $value)
				foreach($value as $k => $v)
				{
					$arr = [
						'shop_id' =>$key,
						'goods_id' =>$k,
						'number' => count($v['uid']),
						'repurchase_num' => $v['repurchase_num'],
						'total_amount' =>$v['total_amount'],
						'deal_time'=>$start_time
					];
					array_push($insertData,$arr);
				}
			 $res = Db::name('shop_goods_analyse')->insertAll($insertData);

			$where = [];
			array_push($where,['b.status','=',2]);
			array_push($where,['a.goods_id','not in',$extra]);
			array_push($where,['b.deal_time','>=',$start_time]);
			array_push($where,['b.deal_time','<=',$end_time]);

			$res = Db::name('shop_order_goods')
				->field('b.shop_id,b.uid,c.goods_type,a.number,a.pay_price')
				->alias('a')
				->join('shop_order b','a.order_id = b.id','LEFT')
				->join('shop_goods c','a.goods_id = c.id')
				->where($where)
				->select()->toArray();


			$firstData = [];
			foreach($res as $value)
			{
				$arr = [];
				if(empty($firstData[$value['shop_id']][$value['goods_type']]))
				{
					$firstData[$value['shop_id']][$value['goods_type']]['number'] = 1;
					$firstData[$value['shop_id']][$value['goods_type']]['uid'] = [];
					array_push($firstData[$value['shop_id']][$value['goods_type']]['uid'],$value['uid']);
					$firstData[$value['shop_id']][$value['goods_type']]['repurchase_num'] = 1;
					$firstData[$value['shop_id']][$value['goods_type']]['total_amount'] = $value['number']*$value['pay_price'];
				}else{
					$firstData[$value['shop_id']][$value['goods_type']]['number'] += 1;
					$firstData[$value['shop_id']][$value['goods_type']]['repurchase_num'] += 1;
					if(!in_array($value['uid'],$firstData[$value['shop_id']][$value['goods_type']]['uid']))
					{
						array_push($firstData[$value['shop_id']][$value['goods_type']]['uid'],$value['uid']);
					}
					$firstData[$value['shop_id']][$value['goods_type']]['total_amount'] += $value['number']*$value['pay_price'];
				}
			}
			$insertData = [];
			foreach($firstData as $key => $value)
				foreach($value as $k => $v)
				{
					$arr = [
						'shop_id' =>$key,
						'goods_type' =>$k,
						'number' => count($v['uid']),
						'repurchase_num' => $v['repurchase_num'],
						'total_amount' =>$v['total_amount'],
						'deal_time'=>$start_time
					];
					array_push($insertData,$arr);
				}
			$res = Db::name('shop_goods_analyse')->insertAll($insertData);

			$where = [];

			array_push($where,['status','=',4]);
			array_push($where,['cancel_time','<>',0]);
			array_push($where,['cancel_time','>=',$start_time]);
			array_push($where,['cancel_time','<',$end_time]);

			$res = Db::name('shop_order')->where($where)->select()->toArray();


			foreach($res as $value)
			{
				if(date('Y-m-d',$value['deal_time']) == date('Y-m-d',$value['cancel_time']))
					{
						continue;
					}
				$orderId = $value['id'];
				$where = [];
				array_push($where,['a.order_id','=',$orderId]);

				$orderGoods = Db::name('shop_order_goods')->alias('a')
					->field('a.goods_id,b.goods_type,a.number,a.pay_price')
					->join('shop_goods b','a.goods_id = b.id')
					->where($where)->find();


				$where = [];
				array_push($where,['shop_id','=',$value['shop_id']]);
				array_push($where,['goods_id','=',$orderGoods['goods_id']]);
				array_push($where,['deal_time','=',strtotime(date('Y-m-d',$value['deal_time']))]);
				$orderGoodsAnalyse = Db::name('shop_goods_analyse')->where($where)->find();
				$UpdateorderGoodsAnalyse['repurchase_num']=$orderGoodsAnalyse['repurchase_num']-1;
				$UpdateorderGoodsAnalyse['total_amount']=$orderGoodsAnalyse['total_amount']-$orderGoods['number']*$orderGoods['pay_price'];

				$where = [];
				array_push($where,['b.uid','=',$value['uid']]);
				array_push($where,['b.deal_time','>=',$value['deal_time']]);
				array_push($where,['b.deal_time','<=',$value['deal_time']+24*60*60-1]);
				array_push($where,['b.shop_id','=',$value['shop_id']]);
				array_push($where,['a.goods_id','=',$orderGoods['goods_id']]);
				$orderGoodsData = Db::name('shop_order_goods')->alias('a')
					->field('a.goods_id,count(b.uid) as num')
					->join('shop_order b','a.order_id = b.id')
					->group('b.uid')
					->where($where)->find();
				if($orderGoodsData['num'] == 1)
				{
					$UpdateorderGoodsAnalyse['number']=$orderGoodsAnalyse['number']-1;
				}

				$where = [];
				array_push($where,['id','=',$orderGoodsAnalyse['id']]);
				 $res = Db::name('shop_goods_analyse')->where($where)->update($UpdateorderGoodsAnalyse);

				$where = [];
				array_push($where,['shop_id','=',$value['shop_id']]);
				array_push($where,['goods_id','=',0]);
				array_push($where,['goods_type','=',$orderGoods['goods_type']]);
				array_push($where,['deal_time','=',strtotime(date('Y-m-d',$value['deal_time']))]);
				$orderGoodsAnalyse = Db::name('shop_goods_analyse')->where($where)->find();
				$UpdateorderGoodsAnalyse['repurchase_num']=$orderGoodsAnalyse['repurchase_num']-1;
				$UpdateorderGoodsAnalyse['total_amount']=$orderGoodsAnalyse['total_amount']-$orderGoods['number']*$orderGoods['pay_price'];

				$where = [];
				array_push($where,['b.uid','=',$value['uid']]);
				array_push($where,['b.deal_time','>=',$value['deal_time']]);
				array_push($where,['b.deal_time','<=',$value['deal_time']+24*60*60-1]);
				array_push($where,['b.shop_id','=',$value['shop_id']]);
				array_push($where,['c.goods_type','=',$orderGoods['goods_type']]);
				$orderGoodsData = Db::name('shop_order_goods')->alias('a')
					->field('c.goods_type,count(b.uid) as num')
					->join('shop_order b','a.order_id = b.id')
					->join('shop_goods c','a.goods_id = c.id')
					->group('b.uid')
					->where($where)->find();

				if($orderGoodsData['num'] == 1)
				{
					$UpdateorderGoodsAnalyse['number']=$orderGoodsAnalyse['number']-1;
				}

				$where = [];
				array_push($where,['id','=',$orderGoodsAnalyse['id']]);
				$res = Db::name('shop_goods_analyse')->where($where)->update($UpdateorderGoodsAnalyse);

			}




			Db::commit();
		} catch (\Exception $e) {
			// 回滚事务
			Db::rollback();
			return json($e->getMessage());
		}
	}
	/**
	 * 客服分析表
	 */
    public function setCustomerAnalyse($date)
    {
        $now = date('Y-m-d',strtotime('-1 day'));

        $bh = [1,2,3,4,5,6,7,8,9];
        $dd = [10];
        $xm = [11,12];

        $start_time = strtotime($date);
        $end_time = strtotime($date)+24*60*60-1;
        $data = [];
        $baseWhere = [];
        $whereOr = [];
        array_push($whereOr,['a.first_time','between',[$start_time,$end_time]]);
        array_push($whereOr,['a.second_time','between',[$start_time,$end_time]]);
        if(!empty($request['shopIds']))
        {
            array_push($baseWhere,['a.shop_id','in',$request['shopIds']]);
        }
        $where = array_merge($baseWhere,[['b.customer_setting_id_type','in',$bh]]);
        $res = Db::name('customer')->alias('a')
            ->join('customer_scar b','a.id = b.customer_id','left')
            ->join('shop c','a.shop_id = c.shop_id','left')
            ->field('count(a.id) as num,a.shop_id,c.shop_name,c.market_name,c.market_id')
            ->where($where)
            ->where(function($query)use($whereOr){
                $query->whereOr($whereOr);
            })
            ->group('a.shop_id')
            ->order('c.market_id')
            ->select()->toArray();
        foreach($res as $value)
        {
            $data[$value['shop_id']]['date'] = $start_time;
            $data[$value['shop_id']]['shop_id'] = $value['shop_id'];
            $data[$value['shop_id']]['bh_store'] = $value['num'];
        }
        $where = array_merge($baseWhere,[['b.customer_setting_id_type','in',$dd]]);
        $res = Db::name('customer')->alias('a')
            ->join('customer_scar b','a.id = b.customer_id','left')
            ->join('shop c','a.shop_id = c.shop_id','left')
            ->field('count(a.id) as num,a.shop_id,c.shop_name,c.market_name,c.market_id')
            ->where($where)
            ->where(function($query)use($whereOr){
                $query->whereOr($whereOr);
            })
            ->group('a.shop_id')
            ->order('c.market_id')
            ->select()->toArray();
        foreach($res as $value)
        {
            $data[$value['shop_id']]['date'] = $start_time;
            $data[$value['shop_id']]['shop_id'] = $value['shop_id'];
            $data[$value['shop_id']]['dd_store'] = $value['num'];
        }
        $where = array_merge($baseWhere,[['b.customer_setting_id_type','in',$xm]]);
        $res = Db::name('customer')->alias('a')
            ->join('customer_scar b','a.id = b.customer_id','left')
            ->join('shop c','a.shop_id = c.shop_id','left')
            ->field('count(a.id) as num,a.shop_id,c.shop_name,c.market_name,c.market_id')
            ->where($where)
            ->where(function($query)use($whereOr){
                $query->whereOr($whereOr);
            })
            ->group('a.shop_id')
            ->order('c.market_id')
            ->select()->toArray();
        foreach($res as $value)
        {
            $data[$value['shop_id']]['date'] = $start_time;
            $data[$value['shop_id']]['shop_id'] = $value['shop_id'];
            $data[$value['shop_id']]['xm_store'] = $value['num'];
        }


        //体验数
        $where = [];
        array_push($where,['b.goods_id','=',168]);
        array_push($where,['c.customer_setting_id_type','in',$bh]);
        if(!empty($request['shopIds']))
        {
            array_push($where,['a.shop_id','in',$request['shopIds']]);
        }
        $res = Db::name('customer')->alias('a')
            ->join('service_log b','a.id = b.customer_id','left')
            ->join('customer_scar c','a.id = c.customer_id','left')
            ->where($where)->where(function($query)use($whereOr){
                $query->whereOr($whereOr);
            })->field('a.shop_id,count(distinct(b.customer_id)) as num')->group('shop_id')->select()->toArray();
        foreach($res as $value)
        {
            $data[$value['shop_id']]['bh_receive']=$value['num'];
        }

        $where = [];
        array_push($where,['b.goods_id','=',150]);
        array_push($where,['c.customer_setting_id_type','in',$dd]);
        if(!empty($request['shopIds']))
        {
            array_push($where,['a.shop_id','in',$request['shopIds']]);
        }
        $res = Db::name('customer')->alias('a')
            ->join('service_log b','a.id = b.customer_id','left')
            ->join('customer_scar c','a.id = c.customer_id','left')
            ->where($where)->where(function($query)use($whereOr){
                $query->whereOr($whereOr);
            })->field('a.shop_id,count(distinct(b.customer_id)) as num')->group('shop_id')->select()->toArray();
        foreach($res as $value)
        {
            $data[$value['shop_id']]['dd_receive']=$value['num'];
        }

        $where = [];
        array_push($where,['b.goods_id','=',165]);
        array_push($where,['c.customer_setting_id_type','in',$xm]);
        if(!empty($request['shopIds']))
        {
            array_push($where,['a.shop_id','in',$request['shopIds']]);
        }
        $res = Db::name('customer')->alias('a')
            ->join('service_log b','a.id = b.customer_id','left')
            ->join('customer_scar c','a.id = c.customer_id','left')
            ->where($where)->where(function($query)use($whereOr){
                $query->whereOr($whereOr);
            })->field('a.shop_id,count(distinct(b.customer_id)) as num')->group('shop_id')->select()->toArray();
        foreach($res as $value)
        {
            $data[$value['shop_id']]['xm_receive']=$value['num'];
        }

        //体验顾客成交数
        $where = [];
        array_push($where,['b.goods_id','=',168]);
        array_push($where,['a.cj_money','>',500]);
        array_push($where,['d.customer_setting_id_type','in',$bh]);
        if(!empty($request['shopIds']))
        {
            array_push($where,['a.shop_id','in',$request['shopIds']]);
        }
        $res = Db::name('customer')->alias('a')
            ->join('service_log b','a.id = b.customer_id','left')
            // ->join('shop_refund_order c','a.id = c.uid')
            ->join('customer_scar d','a.id = d.customer_id','left')
            ->where($where)->where(function($query)use($whereOr){
                $query->whereOr($whereOr);
            })->field('a.shop_id,count(distinct(a.id)) as num')->group('a.shop_id')->select()->toArray();
        foreach($res as $value)
        {
            $data[$value['shop_id']]['bh_receive_deal']=$value['num'];
        }

        $where = [];
        array_push($where,['b.goods_id','=',150]);
        array_push($where,['a.cj_money','>',500]);
        array_push($where,['d.customer_setting_id_type','in',$dd]);
        if(!empty($request['shopIds']))
        {
            array_push($where,['a.shop_id','in',$request['shopIds']]);
        }
        $res = Db::name('customer')->alias('a')
            ->join('service_log b','a.id = b.customer_id','left')
            // ->join('shop_refund_order c','a.id = c.uid')
            ->join('customer_scar d','a.id = d.customer_id','left')
            ->where($where)->where(function($query)use($whereOr){
                $query->whereOr($whereOr);
            })->field('a.shop_id,count(distinct(a.id)) as num')->group('a.shop_id')->select()->toArray();
        foreach($res as $value)
        {
            $data[$value['shop_id']]['dd_receive_deal']=$value['num'];
        }

        $where = [];
        array_push($where,['b.goods_id','=',165]);
        array_push($where,['a.cj_money','>',500]);
        array_push($where,['d.customer_setting_id_type','in',$xm]);
        if(!empty($request['shopIds']))
        {
            array_push($where,['a.shop_id','in',$request['shopIds']]);
        }
        $res = Db::name('customer')->alias('a')
            ->join('service_log b','a.id = b.customer_id','left')
            // ->join('shop_refund_order c','a.id = c.uid')
            ->join('customer_scar d','a.id = d.customer_id','left')
            ->where($where)->where(function($query)use($whereOr){
                $query->whereOr($whereOr);
            })->field('a.shop_id,count(distinct(a.id)) as num')->group('a.shop_id')->select()->toArray();
        foreach($res as $value)
        {
            $data[$value['shop_id']]['xm_receive_deal']=$value['num'];
        }

        //体验金额
        $where = [];
        array_push($where,['b.goods_id','=',168]);
        array_push($where,['d.customer_setting_id_type','in',$bh]);
        array_push($where,['c.business_type','=',1]);
        array_push($where,['c.status','=',2]);
        array_push($where,['c.extra_type','=',0]);
        if(!empty($request['shopIds']))
        {
            array_push($where,['a.shop_id','in',$request['shopIds']]);
        }
        $res = Db::name('customer')->alias('a')
            ->join('service_log b','a.id = b.customer_id','left')
            ->join('shop_refund_order c','a.id = c.uid')
            ->join('customer_scar d','a.id = d.customer_id','left')
            ->where($where)->where(function($query)use($whereOr){
                $query->whereOr($whereOr);
            })->field('a.shop_id,sum(c.pay_amount) as num')->group('shop_id')->select()->toArray();
        foreach($res as $value)
        {
            $data[$value['shop_id']]['bh_receive_money']=$value['num'];
        }
        $where = [];
        array_push($where,['b.goods_id','=',150]);
        array_push($where,['d.customer_setting_id_type','in',$dd]);
        array_push($where,['c.business_type','=',1]);
        array_push($where,['c.status','=',2]);
        array_push($where,['c.extra_type','=',1]);
        if(!empty($request['shopIds']))
        {
            array_push($where,['a.shop_id','in',$request['shopIds']]);
        }
        $res = Db::name('customer')->alias('a')
            ->join('service_log b','a.id = b.customer_id','left')
            ->join('shop_refund_order c','a.id = c.uid')
            ->join('customer_scar d','a.id = d.customer_id','left')
            ->where($where)->where(function($query)use($whereOr){
                $query->whereOr($whereOr);
            })->field('a.shop_id,sum(c.pay_amount) as num')->group('shop_id')->select()->toArray();
        foreach($res as $value)
        {
            $data[$value['shop_id']]['dd_receive_money']=$value['num'];
        }

        $where = [];
        array_push($where,['b.goods_id','=',165]);
        array_push($where,['d.customer_setting_id_type','in',$xm]);
        array_push($where,['c.business_type','=',2]);
        array_push($where,['c.status','=',2]);
        // array_push($where,['c.extra_type','=',0]);
        if(!empty($request['shopIds']))
        {
            array_push($where,['a.shop_id','in',$request['shopIds']]);
        }
        $res = Db::name('customer')->alias('a')
            ->join('service_log b','a.id = b.customer_id','left')
            ->join('shop_refund_order c','a.id = c.uid')
            ->join('customer_scar d','a.id = d.customer_id','left')
            ->where($where)->where(function($query)use($whereOr){
                $query->whereOr($whereOr);
            })->field('a.shop_id,sum(c.pay_amount) as num')->group('shop_id')->select()->toArray();
        foreach($res as $value)
        {
            $data[$value['shop_id']]['xm_receive_money']=$value['num'];
        }

        //直接进店人数
        $where = [];
        array_push($where,['b.goods_id','not in',[168,165,150]]);
        array_push($where,['a.cj_money','>',500]);
        array_push($where,['d.customer_setting_id_type','in',$bh]);
        if(!empty($request['shopIds']))
        {
            array_push($where,['a.shop_id','in',$request['shopIds']]);
        }
        $res = Db::name('customer')->alias('a')
            ->join('service_log b','a.id = b.customer_id','left')
            // ->join('shop_refund_order c','a.id = c.uid')
            ->join('customer_scar d','a.id = d.customer_id','left')
            ->where($where)->where(function($query)use($whereOr){
                $query->whereOr($whereOr);
            })->field('a.shop_id,count(distinct(a.id)) as num')->group('a.shop_id')->select()->toArray();
        foreach($res as $value)
        {
            $data[$value['shop_id']]['bh_direct']=$value['num'];
        }
        $where = [];
        array_push($where,['b.goods_id','not in',[168,165,150]]);
        array_push($where,['a.cj_money','>',500]);
        array_push($where,['d.customer_setting_id_type','in',$dd]);
        if(!empty($request['shopIds']))
        {
            array_push($where,['a.shop_id','in',$request['shopIds']]);
        }
        $res = Db::name('customer')->alias('a')
            ->join('service_log b','a.id = b.customer_id','left')
            // ->join('shop_refund_order c','a.id = c.uid')
            ->join('customer_scar d','a.id = d.customer_id','left')
            ->where($where)->where(function($query)use($whereOr){
                $query->whereOr($whereOr);
            })->field('a.shop_id,count(distinct(a.id)) as num')->group('a.shop_id')->select()->toArray();
        foreach($res as $value)
        {
            $data[$value['shop_id']]['dd_direct']=$value['num'];
        }
        $where = [];
        array_push($where,['b.goods_id','not in',[168,165,150]]);
        array_push($where,['a.cj_money','>',500]);
        array_push($where,['d.customer_setting_id_type','in',$xm]);
        if(!empty($request['shopIds']))
        {
            array_push($where,['a.shop_id','in',$request['shopIds']]);
        }
        $res = Db::name('customer')->alias('a')
            ->join('service_log b','a.id = b.customer_id','left')
            // ->join('shop_refund_order c','a.id = c.uid')
            ->join('customer_scar d','a.id = d.customer_id','left')
            ->where($where)->where(function($query)use($whereOr){
                $query->whereOr($whereOr);
            })->field('a.shop_id,count(distinct(a.id)) as num')->group('a.shop_id')->select()->toArray();
        foreach($res as $value)
        {
            $data[$value['shop_id']]['xm_direct']=$value['num'];
        }
        //直接进店金额
        $where = [];
        array_push($where,['b.goods_id','not in',[168,165,150]]);
        array_push($where,['d.customer_setting_id_type','in',$bh]);
        array_push($where,['c.business_type','=',1]);
        array_push($where,['c.status','=',2]);
        array_push($where,['c.extra_type','=',0]);
        if(!empty($request['shopIds']))
        {
            array_push($where,['a.shop_id','in',$request['shopIds']]);
        }
        $res = Db::name('customer')->alias('a')
            ->join('service_log b','a.id = b.customer_id','left')
            ->join('shop_refund_order c','a.id = c.uid')
            ->join('customer_scar d','a.id = d.customer_id','left')
            ->where($where)->where(function($query)use($whereOr){
                $query->whereOr($whereOr);
            })->field('a.shop_id,sum(c.pay_amount) as num')->group('shop_id')->select()->toArray();
        foreach($res as $value)
        {
            $data[$value['shop_id']]['bh_direct_money']=$value['num'];
        }
        $where = [];
        array_push($where,['b.goods_id','not in',[168,165,150]]);
        array_push($where,['d.customer_setting_id_type','in',$dd]);
        array_push($where,['c.business_type','=',1]);
        array_push($where,['c.status','=',2]);
        array_push($where,['c.extra_type','=',1]);
        if(!empty($request['shopIds']))
        {
            array_push($where,['a.shop_id','in',$request['shopIds']]);
        }
        $res = Db::name('customer')->alias('a')
            ->join('service_log b','a.id = b.customer_id','left')
            ->join('shop_refund_order c','a.id = c.uid')
            ->join('customer_scar d','a.id = d.customer_id','left')
            ->where($where)->where(function($query)use($whereOr){
                $query->whereOr($whereOr);
            })->field('a.shop_id,sum(c.pay_amount) as num')->group('shop_id')->select()->toArray();
        foreach($res as $value)
        {
            $data[$value['shop_id']]['dd_direct_money']=$value['num'];
        }

        $where = [];
        array_push($where,['b.goods_id','not in',[168,165,150]]);
        array_push($where,['d.customer_setting_id_type','in',$xm]);
        array_push($where,['c.business_type','=',2]);
        array_push($where,['c.status','=',2]);
        array_push($where,['c.extra_type','=',0]);
        if(!empty($request['shopIds']))
        {
            array_push($where,['a.shop_id','in',$request['shopIds']]);
        }
        $res = Db::name('customer')->alias('a')
            ->join('service_log b','a.id = b.customer_id','left')
            ->join('shop_refund_order c','a.id = c.uid')
            ->join('customer_scar d','a.id = d.customer_id','left')
            ->where($where)->where(function($query)use($whereOr){
                $query->whereOr($whereOr);
            })->field('a.shop_id,sum(c.pay_amount) as num')->group('shop_id')->select()->toArray();
        foreach($res as $value)
        {
            $data[$value['shop_id']]['xm_direct_money']=$value['num'];
        }
        foreach($data as $key => $value)
        {
            if(empty($value['bh_store']))
            {
                $data[$key]['bh_store']=0;
            }
            if(empty($value['dd_store']))
            {
                $data[$key]['dd_store']=0;
            }
            if(empty($value['xm_store']))
            {
                $data[$key]['xm_store']=0;
            }
            if(empty($value['bh_receive']))
            {
                $data[$key]['bh_receive']=0;
            }
            if(empty($value['dd_receive']))
            {
                $data[$key]['dd_receive']=0;
            }
            if(empty($value['xm_receive']))
            {
                $data[$key]['xm_receive']=0;
            }
            if(empty($value['bh_receive_deal']))
            {
                $data[$key]['bh_receive_deal']=0;
            }
            if(empty($value['dd_receive_deal']))
            {
                $data[$key]['dd_receive_deal']=0;
            }
            if(empty($value['xm_receive_deal']))
            {
                $data[$key]['xm_receive_deal']=0;
            }
            if(empty($value['bh_receive_money']))
            {
                $data[$key]['bh_receive_money']=0;
            }
            if(empty($value['dd_receive_money']))
            {
                $data[$key]['dd_receive_money']=0;
            }
            if(empty($value['xm_receive_money']))
            {
                $data[$key]['xm_receive_money']=0;
            }
            if(empty($value['bh_direct']))
            {
                $data[$key]['bh_direct']=0;
            }
            if(empty($value['dd_direct']))
            {
                $data[$key]['dd_direct']=0;
            }
            if(empty($value['xm_direct']))
            {
                $data[$key]['xm_direct']=0;
            }
            if(empty($value['bh_direct_money']))
            {
                $data[$key]['bh_direct_money']=0;
            }
            if(empty($value['dd_direct_money']))
            {
                $data[$key]['dd_direct_money']=0;
            }
            if(empty($value['xm_direct_money']))
            {
                $data[$key]['xm_direct_money']=0;
            }
            $data[$key]['store_sum']=$data[$key]['bh_store']+$data[$key]['dd_store']+$data[$key]['xm_store'];
            $data[$key]['receive_sum']=$data[$key]['bh_receive']+$data[$key]['dd_receive']+$data[$key]['xm_receive'];
            $data[$key]['receive_deal_sum']=$data[$key]['bh_receive_deal']+$data[$key]['dd_receive_deal']+$data[$key]['xm_receive_deal'];
            $data[$key]['receive_money_sum']=$data[$key]['bh_receive_money']+$data[$key]['dd_receive_money']+$data[$key]['xm_receive_money'];
            $data[$key]['direct_sum']=$data[$key]['bh_direct']+$data[$key]['dd_direct']+$data[$key]['xm_direct'];
            $data[$key]['direct_money_sum']=$data[$key]['bh_direct_money']+$data[$key]['dd_direct_money']+$data[$key]['xm_direct_money'];
            krsort($data[$key]);
        }
        if($now == $date)
        {
            $data = array_merge($data,[]);
            Db::name('shop_customer_analyse')->insertAll($data);
        }else{
            $result = CustomerAnalyseModel::where('date','=',strtotime($date))->column('id','shop_id');
            foreach ($data as $key => $value)
            {
                if(!empty($result[$key]))
                    $data[$key]['id']=$result[$key];
            }
            $data = array_merge($data,[]);
            $model = new CustomerAnalyseModel;
            $model->saveAll($data);

        }
        return true;
    }
	
    public function setCustomerAnalyseControl()
    {
        $start = strtotime('-2 month');
        $end = strtotime('-1 day');
        while($start<=$end)
        {
            $this->setCustomerAnalyse(date('Y-m-d',$start));
            $start+=24*60*60;
        }
    }

    public function updateLoginType()
    {
        
        $where = [];

        array_push($where,['type','in',[1,3]]);
        array_push($where,['shop_id','<>','74076159037951']);
        array_push($where,['status','=','1']);

        $shop_list = DB::name('shop')->where($where)->column('shop_id');

        $where = [];

        array_push($where,['status','=',3]);
        array_push($where,['leave_at','>',"2024-05-01"]);
        array_push($where,['shop_id','in',$shop_list]);

        $leave_person = Db::name('shop_person')->where($where)->column('id');

        $customer = Db::name('customer')->where('nurse_id','in',$leave_person)->column('shop_id');

        $shop_ids = array_unique($customer);

        $where = [];

        array_push($where,['shop_id','in',$shop_ids]);
        array_push($where,['status','=',1]);
        array_push($where,['station_id','=',13]);

        $zl = Db::name('shop_person')->where($where)->column('id');

        foreach ($zl as $key => $value) {
            
            Db::name('shop_person')->where('id','=',$value)->update(['$status' => 2]);

        }

    }


	// 凌晨执行
	public function execute()
	{
		$this->customer_tj(); // 统计每日截至当前时间成交个数，保有个数，流失预警，流失个数数据
		
		$this->setOrderGoodsAnalyse(); //执行每天品项分析数据报表

		// $this->setCustomerAnalyseControl(); //执行每天客户分析数据报表

		$this->updateLoginType(); // 执行每天查询门店是否有离职员工

		// $model = new SendMsgModel();

  //       $model->everydaytask();

		return resultArray(['data'=>[],'error'=>'处理成功']);
		// $this->set_ceshi();
	}

	// 凌晨执行  --郑州太原市场
	public function setztmaktingyc()
	{
		$this->setCustomerZTYuCun();  //郑州太原市场

		return resultArray(['data'=>[],'error'=>'处理成功']);
	}

	// 凌晨执行
	public function setkmxianmaktingyc()
	{
		$this->setCustomerKXYuCun(); //昆明西安市场
		
		return resultArray(['data'=>[],'error'=>'处理成功']);
	}


    // 凌晨执行 东北市场
	public function setdjmaktingyc()
	{
		$this->setCustomerDJYuCun(); //执行新增门店的客户预存数据--2023-05-11

		return resultArray(['data'=>[],'error'=>'处理成功']);
	}
	
	// 凌晨执行 川渝市场
	public function setcdcqmaktingyc()
	{
		$this->setCustomerCYYuCun(); 
	
		return resultArray(['data'=>[],'error'=>'处理成功']);
	}
	
	// 凌晨执行 济南石家庄市场
	public function setjsmaktingyc()
	{
		$this->setCustomerJSYuCun(); 
	
		return resultArray(['data'=>[],'error'=>'处理成功']);
	}
	
	
	// 凌晨执行 郑州直管+成都2家 +烟台
	public function setzgtmaktingyc()
	{
		$this->setCustomerZCYYuCun(); 
	
		return resultArray(['data'=>[],'error'=>'处理成功']);
	}
	
	// 凌晨执行 北京+烟青潍市场
	public function setjmbjmaktingyc()
	{
		$this->setCustomerBJYYuCun(); 
	
		return resultArray(['data'=>[],'error'=>'处理成功']);
	}
	
	
	
	// 凌晨执行 北京+烟青潍市场
	public function setzxunmaktingyc()
	{
		$this->setCustomerZHUXUNYuCun(); 
	
		return resultArray(['data'=>[],'error'=>'处理成功']);
	}
}
